package pl.enigmatic.parser.string.java.awt;

import java.awt.Font;

import pl.enigmatic.parser.string.ArrayConverter;
import pl.enigmatic.parser.string.Converter;


public class FontConverter extends Converter<Font> {

	public final static String PLAIN = "plain";
	public final static String BOLD = "bold";
	public final static String ITALIC = "italic";

	ArrayConverter<String> array = new ArrayConverter<String>(String.class, ArrayConverter.COMMA_PATTERN, ArrayConverter.COMMA_SEPARATOR);

	private int parseStyle(String value) {
		value = value.toLowerCase();
		if (value.equals(BOLD + PLAIN) || value.equals(PLAIN + BOLD)) { return Font.ITALIC | Font.BOLD; }
		int res = Font.PLAIN;
		for (final String style : value.replace(" ", "").toLowerCase().split("\\+")) {
			if (BOLD.equals(style)) {
				res |= Font.BOLD;
			} else if (ITALIC.equals(style)) {
				res |= Font.ITALIC;
			}
		}
		return res;
	}

	public Font convert(final String[] params) {
		if (params.length == 1) {
			return new Font(params[0], Font.PLAIN, 1);
		} else if (params.length == 2) {
			return new Font(params[0], parseStyle(params[1]), 1);
		} else if (params.length >= 3) {
			return new Font(params[0], parseStyle(params[1]), Integer.parseInt(params[2]));
		} else {
			return new Font(null);
		}
	}

	@Override
	public Font convert(final String value) {
		return convert(array.convert(value));
	}

	@Override
	public String convertBack(final Font value) {
		return array.convertBack(new String[] {
				value.getName(),
				value.isPlain() ? PLAIN : (value.isBold() ? BOLD : "") + (value.isBold() && value.isItalic() ? "+" : "")
						+ (value.isItalic() ? ITALIC : ""), Integer.toString(value.getSize()) });
	}
}
